const express = require('express');
const mysql = require('mysql2');
const app = express();
const PORT = 3000;

// 创建 MySQL 连接池
const pool = mysql.createPool({
    host: '47.238.28.110',
    user: 'root',
    port: '3306',
    password: 'Wz@9fK3#LmX$8pQ7',
    database: 'user',
});

// 测试 MySQL 连接
pool.getConnection((err, connection) => {
    if (err) {
        console.error('MySQL 连接失败:', err);
    } else {
        console.log('MySQL 连接成功');
        connection.release();
    }
});

// 中间件：解析 JSON 请求体
app.use(express.json());


// 路由：登录
app.post('/login', (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).json({ operate: false, message: '用户名和密码不能为空' });
    }

    // 查询数据库验证用户
    pool.query(
        'SELECT * FROM users WHERE username = ? AND password = ?',
        [username, password],
        (err, results) => {
            if (err) {
                console.error('查询数据库失败:', err);
                return res.status(500).json({ operate: false, message: '服务器错误' });
            }

            if (results.length > 0) {
                // 返回查到的所有字段
                const user = results[0];
                res.json({
                    operate: true,
                    msg: "登陆成功!",
                    data: {
                        id: user.id,
                        username: user.username,
                        password: user.password,
                        nickname: user.nickname,
                        tel: user.tel,
                        email: user.email,
                        reset_question: user.reset_question,
                        reset_answer: user.reset_answer,
                        avatar: user.avatar,
                    },
                });
            } else {
                res.status(400).json({ operate: false, message: '用户名或密码错误' });
            }
        }
    );
});

// 路由：注册
app.post('/register', (req, res) => {
    const { username, password, nickname, tel, email, reset_question, reset_answer } = req.body;

    // 检查必填字段
    if (!username || !password || !nickname || !tel || !email || !reset_question || !reset_answer) {
        return res.status(400).json({ operate: false, message: '所有字段都是必填项' });
    }

    // 插入用户数据
    pool.query(
        'INSERT INTO users (username, password, nickname, tel, email, reset_question, reset_answer) VALUES (?, ?, ?, ?, ?, ?, ?)',
        [username, password, nickname, tel, email, reset_question, reset_answer],
        (err, results) => {
            if (err) {
                console.error('用户注册失败:', err);
                return res.status(500).json({ operate: false, message: '服务器错误' });
            }
            res.json({ operate: true, message: '用户注册成功', userId: results.insertId });
        }
    );
});


// 路由：重置密码（预留）
app.post('/reset_pwd', (req, res) => {
    res.json({ operate: false, message: '重置密码功能尚未实现' });
});

// 路由：删除用户（预留）
app.delete('/del_user', (req, res) => {
    res.json({ operate: false, message: '删除用户功能尚未实现' });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
